/**
 * 测试1119指令返回格式
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    }
};

class Test1119Format {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
    }

    async runTest() {
        console.log('🎯 测试1119指令返回格式...\n');

        try {
            await this.testHttpLogin();
            await this.testWebSocketConnection();
            await this.test1119Format();
            await this.testDisconnect();
        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
        }
    }

    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录测试...');
        try {
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;
                console.log(`✅ 登录成功: userId=${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }
        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            throw error;
        }
    }

    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接测试...');
        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');
                    await this.delay(500);
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    reject(error);
                });

                setTimeout(() => {
                    if (this.ws.readyState === WebSocket.CONNECTING) {
                        this.ws.close();
                        reject(new Error('连接超时'));
                    }
                }, 10000);
            } catch (error) {
                reject(error);
            }
        });
    }

    async test1119Format() {
        console.log('\n📋 步骤3: 测试1119指令返回格式...');
        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                this.ws.removeListener('message', handler);
                console.log('⚠️ 1119指令测试超时');
                resolve();
            }, 10000);

            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && msg.act_id === 1119) {
                        clearTimeout(timeout);
                        this.ws.removeListener('message', handler);

                        console.log('📨 收到1119指令响应:');
                        console.log(JSON.stringify(msg, null, 2));

                        if (msg.code === 0 && msg.list) {
                            console.log('\n🔍 验证返回格式:');
                            msg.list.forEach((deputy, index) => {
                                console.log(`\n副将 ${index + 1}:`);
                                console.log(`  id: ${deputy.id} (类型: ${typeof deputy.id})`);
                                console.log(`  lvl: ${deputy.lvl} (类型: ${typeof deputy.lvl})`);
                                console.log(`  name: "${deputy.name}" (类型: ${typeof deputy.name})`);
                                console.log(`  pos: ${deputy.pos} (类型: ${typeof deputy.pos})`);
                                console.log(`  roleType: ${deputy.roleType} (类型: ${typeof deputy.roleType})`);
                                console.log(`  s: ${deputy.s} (类型: ${typeof deputy.s})`);
                                console.log(`  star: ${deputy.star} (类型: ${typeof deputy.star})`);

                                // 验证格式是否符合要求
                                const requiredFields = ['id', 'lvl', 'name', 'pos', 'roleType', 's', 'star'];
                                const hasAllFields = requiredFields.every(field => field in deputy);

                                if (hasAllFields) {
                                    console.log(`  ✅ 格式验证通过 - 包含所有必需字段`);
                                } else {
                                    console.log(`  ❌ 格式验证失败 - 缺少必需字段`);
                                }
                            });

                            // 检查是否与标准格式一致
                            const standardFormat = { "id": 86849, "lvl": 66, "name": "武斗家", "pos": 3, "roleType": 1, "s": 4, "star": 1 };
                            const sampleDeputy = msg.list[0];
                            if (sampleDeputy) {
                                const formatMatch = Object.keys(standardFormat).every(key => key in sampleDeputy);
                                if (formatMatch) {
                                    console.log('\n🎉 格式完全匹配标准指令格式！');
                                } else {
                                    console.log('\n⚠️ 格式与标准指令格式不完全匹配');
                                }
                            }
                        } else {
                            console.log('❌ 1119指令执行失败:', msg.msg || '未知错误');
                        }
                        return resolve();
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1119, d: null }));
        });
    }

    async testDisconnect() {
        console.log('\n🔌 步骤4: 断开WebSocket连接...');
        if (this.ws) {
            this.ws.close();
        }
    }

    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, res => {
                let body = '';
                res.on('data', (chunk) => { body += chunk; });
                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => { reject(error); });
            if (data) { req.write(JSON.stringify(data)); }
            req.end();
        });
    }

    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

async function main() {
    const tester = new Test1119Format();
    await tester.runTest();
}

if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = Test1119Format;
